/*

  The MIT License

  Copyright (c) 2008 - 2010. Dimarik

  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files (the "Software"), to deal
  in the Software without restriction, including without limitation the rights
  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  copies of the Software, and to permit persons to whom the Software is
  furnished to do so, subject to the following conditions:

  The above copyright notice and this permission notice shall be included in
  all copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  THE SOFTWARE.

*/

package ru.goodcore.display
{

import flash.display.Loader;
import flash.display.LoaderInfo;
import flash.events.ErrorEvent;
import flash.events.Event;
import flash.events.HTTPStatusEvent;
import flash.events.IOErrorEvent;
import flash.events.ProgressEvent;
import flash.net.URLRequest;
import flash.system.LoaderContext;
import flash.utils.ByteArray;
import flash.utils.Endian;


/**
 * 
 * 
 * @author				Dimarik
 * @version				1.2
 * @langversion			3.0
 * @playerversion		9.0
 * 
 *  • Load successfull
 * 	FIRE unload (optional)  original
 *	FIRE open               original
 *	FIRE progress           original
 *	FIRE progress           original
 *	FIRE init               secondary
 *	FIRE httpStatus         secondary
 *	FIRE complete           secondary
 * 
 *  • Load fail
 * 	FIRE unload (optional)  original
 *	FIRE open               original
 *	FIRE progress           original
 *	FIRE progress           original
 *	FIRE httpStatus         original
 *	FIRE ioError            original
 */
public final class GIFLoaderAdv extends Loader {

	//-------------------------------------------------------------------------
	//
	//   Class methods
	//
	//-------------------------------------------------------------------------

	//-------------------------------------------------------------------------
	//
	//   Constructor
	//
	//-------------------------------------------------------------------------

	/**
	 * Constructor
	 */
	public function GIFLoaderAdv(
								frameRate:	uint = 0,
								smooth:		Boolean = false
	) {
		super();
		this._smooth	= smooth;
		this._frameRate	= frameRate & 0xFF;

		var li:LoaderInfo = this.contentLoaderInfo; // super, но парсер лох.

		li.addEventListener(Event.UNLOAD,						this.handler_passOnLoadPhase,	false, int.MAX_VALUE);
		li.addEventListener(Event.OPEN,							this.handler_passOnLoadPhase,	false, int.MAX_VALUE);
		li.addEventListener(ProgressEvent.PROGRESS,				this.handler_passOnLoadPhase,	false, int.MAX_VALUE);
		li.addEventListener(Event.INIT,							this.handler_skipOnLoadPhase,	false, int.MAX_VALUE);
		li.addEventListener(HTTPStatusEvent.HTTP_STATUS,		this.handler_skipOnLoadPhase,	false, int.MAX_VALUE);
		li.addEventListener(IOErrorEvent.IO_ERROR,				this.handler_passOnLoadPhase,	false, int.MAX_VALUE);

		li.addEventListener(Event.COMPLETE,						this.handler_complete,			false, int.MAX_VALUE);
	}

	//-------------------------------------------------------------------------
	//
	//   Overridden properties: Loader
	//
	//-------------------------------------------------------------------------

	//-------------------------------------------------------------------------
	//
	//   Properties
	//
	//-------------------------------------------------------------------------

	//---------------------------------
	//  qname
	//---------------------------------
	/**
	 * @private 
	 */
	private var _qname:			QName;

	public function set qname(value:QName):void {
		if (this._qname === value)
			return;

		this._qname = value;
	}

	public function get qname():QName {
		return this._qname;
	}

	//-------------------------------------------------------------------------
	//
	//   Private variables
	//
	//-------------------------------------------------------------------------

	/**
	 * @private 
	 */
	private var _loadPhase:		Boolean = true;

	/**
	 * @private 
	 */
	private var _smooth:		Boolean;

	/**
	 * @private 
	 */
	private var _frameRate:		uint;

	/**
	 * @private 
	 */
	private var _context:		LoaderContext;

	/**
	 * @private 
	 */
	private var _url:			String;

	//-------------------------------------------------------------------------
	//
	//   Overridden methods: Loader
	//
	//-------------------------------------------------------------------------

	/**
	 * @inheritDoc
	 */
	public override function load(request:URLRequest, context:LoaderContext = null):void {
		this._loadPhase = true;
		this._context = context;
		this._url = request.url;
		super.load(request, context);
	}

	/**
	 * @inheritDoc
	 */
	public override function loadBytes(bytes:ByteArray, context:LoaderContext=null):void {
		this._loadPhase = false;
		this._context = context;
		this.loadGIF(bytes);
	}

	//-------------------------------------------------------------------------
	//
	//   Private methods
	//
	//-------------------------------------------------------------------------

	/**
	 * @private
	 */
	private function loadGIF(ba:ByteArray):void {

		if ( !this._qname ) { // Не задан пакет и класс 
			const regExp:	RegExp = /^.*?:\/\/(?P<url>.*)\/(?P<localName>.*)$/;
			var url:		String = this._url || int(Math.random() * 1e6).toString(36);
			const o:		Object = url.match(regExp);

			url = 'ru.goodcore.resource.$.' + String(o.url).replace(/\W/g, '.');
			const localName:String = o.localName ? String(o.localName).replace(/\W/g, '_') : 'Resource';
			this._qname = new QName( url, localName );
		}

		const swf:ByteArray = new SWFGIFMovieClipDocClass(ba, this._qname, this._frameRate, this._smooth);

		if (this._context)
			this._context.securityDomain = null;

		super.loadBytes( swf, this._context );

		this._context = null;
		this._qname = null;
		this._url = null;
	}

	//-------------------------------------------------------------------------
	//
	//   Event handlers
	//
	//-------------------------------------------------------------------------

	/**
	 * @param event
	 */
	private function handler_skipOnLoadPhase(event:Event):void {
		if ( this._loadPhase ) {
			if (event.type === HTTPStatusEvent.HTTP_STATUS) {
				if ( (event.target as LoaderInfo).content != null ) // Нормально загрузилось
					event.stopImmediatePropagation(); // Диспатч будет позже.
			} else {
				event.stopImmediatePropagation();
			}
		}
	}

	/**
	 * @param event
	 */
	private function handler_passOnLoadPhase(event:Event):void {
		if ( !this._loadPhase ) {
			event.stopImmediatePropagation();
		} else {
			if (event is ErrorEvent) {
				this._loadPhase = false;
				this.loadGIF( new ByteArray() );
			}
		}
	}

	/**
	 * 
	 * @param event
	 * 
	 */
	private function handler_complete(event:Event):void {
		if ( !this._loadPhase )
			return;

		event.stopImmediatePropagation();
		this._loadPhase = false;

		var ba:ByteArray = super.contentLoaderInfo.bytes;
		ba.endian = Endian.LITTLE_ENDIAN;

		// Читаем до 0xBF [17]h (DefineBitsJPEG4)
		while ( ba.readUnsignedByte() != 0xBF ) void;
		ba.position += 7;
		var len:uint = ba.readUnsignedInt(); // Размер гифки в байтах		
		ba.position += 2; // skip DeblockParam
		ba.readBytes(ba, 0, len);
		ba.position = 0;
		this.loadGIF(ba);
	}

}
}
